import React, { Component } from 'react';
import { Form, Input,  message, Select, Checkbox, Button, Radio, DatePicker ,Tag   } from 'antd';
import ProductModal from '../../../components/Coupon/ProductModal/index'
import SelectProductModal from '../../../components/Coupon/SelectProductModal'
// import tool from '../../../utils/commonFuc'
import couponApi from '../../../api/coupon'
import { withRouter } from 'react-router-dom'
import moment from 'moment';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const dateFormat = "YYYY-MM-DD HH:mm";

// function hasErrors(fieldsError) {
//   return Object.keys(fieldsError).some(field => fieldsError[field]);
// }

class RegistrationForm extends Component {
  state = {
    confirmDirty: false,
    btnLoading:false,//提交按钮加载状态
    value1: "1",
    productList:[],
    modalData:{
      visible: false
    },
    startTime:undefined,//开始时间
    endTime:undefined,  //结束时间    
    couponData:{
      name:"",
      type:"",
      discount:"",
      num:'1',
      countLimit:"",
      useLimit:"",
      time:"",
      begainTime:"",
      endTime:"",
      productIds:[],
      canAdd:"",
      remark:"",
    }    
  };

  componentWillMount(){
    //获取业务层次
    this.props.onCheckBusinessLevelSelect({});            
  }

  // 设置不可选的日期范围,今天以前的都不可选
  disabledDate = (current)=> {
    let _oneDayMs = 24 * 60 * 60 * 1000;
    return current && current.valueOf() < (Date.now() - _oneDayMs);
  }

  // 设置不可选的时间范围,当前时间点以前的都不可选
  disabledDateTime = () => {
    let _myDate = new Date();
    return {
      disabledHours: () => this.range(0, 24).splice(0,_myDate.getHours()),
      disabledMinutes: () => this.range(0,_myDate.getMinutes()),
    };
  }  

  range = (start, end) => {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }  

  //选择开始时间
  onBeginTimeChange = (date,dateString) => {
    this.onFormChange('begainTime',dateString)
    this.setState({
      startTime:dateString
    })
  }  
  //选择结束时间
  onEndTimeChange = (date,dateString) => {
    this.onFormChange('endTime',dateString)
    this.setState({
      endTime:dateString
    })    
  }  

  //动态改变form表单绑定的值
  onFormChange = (key,value,type="stateSet")=>{
    console.log(key)
    if(type == 'stateSet'){
      this.setState({
        couponData:Object.assign({},this.state.couponData,{
          [key]:value
        })
      },()=>{
        console.log(this.state.couponData)
      })
    }else{
      this.props.form.setFieldsValue({[key]:value})   
    }
  }
  
  // 点击"全部产品"按钮
  onAllProductChange = (e) =>{
    let _productIds = [];
    if(e.target.checked){
      _productIds = [-1];
    }else if(this.state.productList.length > 0){
      this.state.productList.forEach(element => {
        _productIds.push(element.id);
      });
    }
       
    this.setState({
      couponData:Object.assign({},this.state.couponData,{
        productIds:_productIds
      })
    })    
  }
  //创建优惠券
  handleSubmit = (e) => {    
    e.preventDefault();
    const form  = this.props.form;
    const {begainTime,endTime} = this.state.couponData;
    const state = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
        console.log(this.state.couponData)
        if(state.couponData.productIds.length == 0){
          message.error('请选择产品!');
        }else if(form.getFieldValue('state.couponData.time') == "1" && ( !begainTime || !endTime)){
          message.error('请选择开始时间和结束时间!');
        } else{
          this.setState({
            btnLoading:true
          })
          let _obj = Object.assign({},this.state.couponData,values.state.couponData);    
          couponApi.createCoupon(_obj,(status)=>{
            if(status){
              message.success('创建成功');
              this.props.history.goBack();
            }else{
              this.setState({
                btnLoading:false
              })   
            }              
          })
        }
      }else{
        console.log(err)
      }
    });
  }
  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }
  showModal = () => {
    this.setState({
      modalData:{
        visible: true
      }
    });
  }  
  //选择产品页面点击保存
  onOk = (data) => {    
    let _array = [];
    if(data.length>0){        
      data.forEach(item1 => {
        let _isNew = this.state.productList.some((item2) => (item1.id == item2.id));
        if(!_isNew){
          _array.push({
            id:item1.id,
            name:item1.name
          })
        }
      });        
    }      

    let productIds = [];
    let productList = [...this.state.productList,..._array];
    if(productList.length>0){
      productList.forEach(item => {
        productIds.push(item.id)
      });
    }

    this.setState({
      modalData:{
        visible: false
      },
      productList:productList,
      couponData:Object.assign({},this.state.couponData,{productIds})
    });

  }
  onCancel = () => {
    this.setState({
      modalData:{
        visible: false
      }
    });
  }  
  checkPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('Two passwords that you enter is inconsistent!');
    } else {
      callback();
    }
  }
  checkName = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['name'], { force: true });
    }
    callback();
  }

  //校验使用范围
  useLimitValidator = (rule, value, callback) => {
    const form = this.props.form;   
    if (form.getFieldValue('state.couponData.type') == 2 && (value === "" || value === undefined)) {
      // form.validateFields(['state.couponData.useLimit'], { force: true });      
      callback('请输入使用范围')
      return;
    }else if(form.getFieldValue('state.couponData.type') == 2 && value && !/^[0-9]+(.[0-9]{2})?$/.test(value) && !/^[0-9]+(.[0-9]{1})?$/.test(value)){
      callback('仅允许输入数字，精确到小数点后2位');
      return;      
    }else if(form.getFieldValue('state.couponData.type') == 2 && parseFloat(value) <= parseFloat(form.getFieldValue('state.couponData.discount'))){      
      callback('适用条件金额需大于优惠券金额');
      return;   
    }    
    callback();
  }
  // 校验优惠金额或折扣
  discountValidator = (rule, value, callback) => {
    const form = this.props.form;    
    if(form.getFieldValue('state.couponData.type') != 3){
      if(value && !/^[0-9]+(.[0-9]{2})?$/.test(value) && !/^[0-9]+(.[0-9]{1})?$/.test(value)){
        callback('仅允许输入数字，精确到小数点后2位');
        return;
      }else if(parseFloat(value) > 10000){
        callback('最大输入金额不能大于10000');
        return;        
      }
    }else{
      if(value && (!/^([1-9])+(.[0-9]{1})?$/.test(value) || parseFloat(value) > 9.9)){
        callback('请输入1-9.9间之间的数字，精确到小数点后1位');
        return;
      }
    }
    callback(); 
  }
  // 校验发行数量
  countLimitValidator = (rule, value, callback) => {
    const form = this.props.form;   
    const { num } = this.state.couponData;

    if(num == "1" && (!value || parseFloat(value) > 5000 || parseFloat(value) < 1 || !/^[0-9]*$/.test(value))){
      callback('输入发放数量，1-5000'); 
      return;
    }
    callback();
    
  }
  //
  handleTypeChange = (type) =>{
    
  }
  render() {
    const { getFieldDecorator,getFieldValue, getFieldsError, getFieldError, isFieldTouched } = this.props.form;
    const state = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 27 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    return (
      <div>
        {/* 选择产品弹窗 */}
        {/* <ProductModal 
          businessLevelSelect={ this.props.businessLevelSelect }
          productList={ this.props.productList }
          productListTotal={ this.props.productListTotal }
          onCheckProduct={ (data)=> this.props.onCheckProduct(data) } 
          modalData={state.modalData} 
          onOk={this.onOk.bind(this)} 
          onCancel={this.onCancel.bind(this)}/> */}
        <SelectProductModal
            modalData={state.modalData}
            onOk={this.onOk.bind(this)}
            onCancel={this.onCancel.bind(this)}
          ></SelectProductModal>
        <Form onSubmit={this.handleSubmit}>
          <FormItem
            {...formItemLayout}
            label="优惠券类型"
          >
            {getFieldDecorator('state.couponData.type', {
              rules: [{
                required: true, message: '请选择优惠券类型',
              }],
              onChange:()=>{
                this.props.form.setFieldsValue({'state.couponData.discount':""})
              }
            })(
              <Select
              showSearch
              style={{ width: 500 }}
              placeholder="优惠券类型"
              optionFilterProp="children"
              onChange={this.handleChange}
              filterOption={(input, option) => option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0}
              >
                  <Option value="1">抵扣优惠券</Option>
                  <Option value="2">满减优惠券</Option>
                  <Option value="3">折扣优惠券</Option>
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="优惠券名称"
          >
            {getFieldDecorator('state.couponData.name', {
              rules: [{
                required: true, message: '请输入优惠券名称',
              }],
              // onChange: (e) => {
              //   this.onFormChange('state.couponData.discount',tool.inputFilfter(e.target.value,2),'formSet')
              // }              
            })(
              <Input placeholder="优惠券名称" style={{ width: 500 }} maxLength={15}/>
            )}
          </FormItem>
          <div className={getFieldValue('state.couponData.type') == 3?'dn':''}>
            <FormItem
              {...formItemLayout}
              label="优惠券金额"
            >
              {getFieldDecorator('state.couponData.discount', {
                rules: [{
                  required: true, 
                  message:'请输入优惠券金额'                                  
                },{
                  validator:this.discountValidator
                }],
                
              })(              
                <Input placeholder="优惠券金额"  style={{ width: 500 }}/>
              )}
            </FormItem>
          </div>        
          <div className={getFieldValue('state.couponData.type') != 3?'dn':''}>
            <FormItem
              {...formItemLayout}
              label="折扣额度"      
            >
              {getFieldDecorator('state.couponData.discount', {
                rules: [{
                  required: true, 
                  message:'请输入折扣额度'                                  
                },{
                  validator:this.discountValidator
                }],
                
              })(              
                <Input  placeholder="请输入1-9.9间之间的数字，精确到小数点后1位"  style={{ width: 500 }}/>
              )}
            </FormItem> 
          </div>
          <FormItem
            {...formItemLayout}
            label="是否可叠加"
          >
            {getFieldDecorator('state.couponData.canAdd',{initialValue:"0"})(
              <RadioGroup>
                <Radio value="0">是</Radio>
                <Radio value="1">否</Radio>
              </RadioGroup>
            )}
          </FormItem>       
          <FormItem
            {...formItemLayout}
            label="有效时间"
          >
            {getFieldDecorator('state.couponData.time',{
              initialValue:"1",
              onChange: (e) => {
                if(e.target.value == 2){
                  //清空开始时间和结束时间
                  this.onFormChange('begainTime',"");
                  setTimeout(()=>{
                    this.onFormChange('endTime',""); 
                  },0)
                  this.setState({
                    startTime:'',
                    endTime:'',
                  }) 
                }
                
              }
            })(
              <RadioGroup>
                <div style={{ display: 'inline-block' }}>
                <Radio value="1">                
                    <span>开始时间</span>
                    <DatePicker
                      style={{ marginLeft:10 }}
                      showTime
                      disabledDate={this.disabledDate}
                      disabledTime={this.disabledDateTime}
                      format={dateFormat}
                      placeholder="开始时间"
                      value={state.startTime===undefined||state.startTime===""?null:moment(state.startTime, dateFormat)}
                      onChange={this.onBeginTimeChange}
                      // onOk={onOk}
                    />         
                    <span style={{ marginLeft:10 }}>结束时间</span>
                    <DatePicker
                      style={{ marginLeft:10 }}
                      showTime
                      format={dateFormat}
                      placeholder="结束时间"
                      value={state.endTime===undefined||state.endTime===""?null:moment(state.endTime, dateFormat)}
                      onChange={this.onEndTimeChange}
                      // onOk={onOk}
                    />                                     
                </Radio>
                </div>     
                <Radio value="2">不限时间</Radio>
              </RadioGroup>
            )}
          </FormItem>         
          <FormItem
            {...formItemLayout}
            label="发行数量"
          >
            <RadioGroup value={ state.couponData.num } onChange={(e)=>{
              this.setState({
                couponData: Object.assign({},state.couponData,{
                  num:e.target.value
                }),
              });
              this.props.form.setFieldsValue({
                "state.couponData.countLimit":0
              })
            }}>
              <Radio value="1">
                <span>限量</span>
                {getFieldDecorator('state.couponData.countLimit',{
                  rules:[{
                    validator: this.countLimitValidator,
                  }],
                  })(
                  <Input disabled={ state.couponData.num === "0"?true:false } placeholder=" 输入发放数量，1-5000" style={{ width: 200,marginLeft:10 }}/>                              
                )}
              </Radio>
              <Radio value="0">不限量</Radio>
            </RadioGroup>
          </FormItem>        
          <div className={getFieldValue('state.couponData.type') != 2?'dn':''}>
            <FormItem
              {...formItemLayout}
              label="适用条件"
            >
              {getFieldDecorator('state.couponData.useLimit', {
                rules: [{
                  message: '请输入适用条件',
                }, {
                  validator: this.useLimitValidator,
                }],
              })(
                <div>
                  <span>满</span>
                  <Input style={{ width: 100,margin:'0 10px' }}/>       
                  <span>减</span>
                </div>
              )}
            </FormItem>     
          </div>          
          <FormItem
            {...formItemLayout}
            label="适用范围"
          >
            {getFieldDecorator('radio-group',{initialValue:"1"})(
              <div>
                <div>
                  <Button type="primary" className="mr10"  onClick={this.showModal}>选择产品</Button>
                  <span>优惠券创建后，指定产品只能添加，不能删除</span>
                </div>
                <div>
                  {
                    state.productList.map((item,index)=>(
                      <Tag closable key={ index }>{ item.name }</Tag>
                    ))
                  }
                </div>
                <Checkbox onChange={this.onAllProductChange}>全部产品</Checkbox>
              </div>
            )}
          </FormItem>         
          <FormItem
            {...formItemLayout}
            label="是否绑定名片"
          >
            {getFieldDecorator('state.couponData.bindCard',{initialValue:"1"})(
              <RadioGroup>
                <Radio value="1">是</Radio>
                <Radio value="0">否</Radio>
              </RadioGroup>
            )}
          </FormItem>          
          <FormItem
            {...formItemLayout}
            label="优惠券说明"
          >
            {getFieldDecorator('state.couponData.remark')(
              <div>
                <TextArea style={{ width:500 }} placeholder="优惠券说明" autosize={{ minRows: 6, maxRows: 6 }}  maxLength={ 500 }/>
              </div>
            )}
          </FormItem>    
          <FormItem>
            {/* <Button
              type="primary"
              htmlType="submit"
              disabled={hasErrors(getFieldsError())}
            >
              创建
            </Button>     */}
          <Button type="primary" loading={ state.btnLoading } htmlType="submit" style={{ marginLeft:300 }}>创建</Button>            
          <Button type="primary" style={{ marginLeft:10 }} onClick={() => { this.props.history.goBack() }}>返回</Button>        
          </FormItem>            
        </Form>
      </div>
    );
  }
}

const WrappedRegistrationForm = withRouter(Form.create({})(RegistrationForm));
export default WrappedRegistrationForm;